package com.nerve.android.cloudoffice.app.worker;

import org.nerve.android.net.NetWorker;

import android.os.Handler;
import android.os.Message;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.service.data.MessageData;

/**
 * @project: Cloudoffice_android
 * @file: LoadMessageWorkder.java
 * @package: com.nerve.android.cloudoffice.app.worker
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 22, 2013
 * @change log:
 */
public class LoadMessageWorkder extends Thread{

	public final static int LOAD_MESSAGE_DONE = 2000;
	public final static int LOAD_MESSAGE_FAIL = 2001;
	
	private Handler handler;
	private int userId;
	private long sleepTime;
	private boolean isCancel;
	
	public LoadMessageWorkder(int userId, Handler handler, long time){
		this.handler = handler;
		this.userId = userId;
		this.sleepTime = time;
	}
	
	@Override
	public synchronized void start() {
		this.isCancel = false;
		super.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		while(!isCancel){
			try{
				Thread.sleep(sleepTime);
				
				if(NetWorker.isConnect(OfficeApplication.context)){
					Reply re = MessageData.loadMessageFromServer(userId);
					android.os.Message msg = new Message();
					msg.what = LOAD_MESSAGE_DONE;
					msg.arg1 = Integer.valueOf(re.getMessage().toString());
					
					handler.sendMessage(msg);
				}
			}catch(Exception e){
				
			}
		}
	}
	
	public void cancel(){
		this.isCancel = true;
		
		Const.log("***************** 加载消息的线程被暂停了！****************");
	}
	
	public void restart(){
		this.isCancel = false;
	}
}